import { memo, useEffect } from 'react'
import styles from './Login.module.scss'
import { Typography, Form, Button, Space, Input, Checkbox, message } from 'antd'
import { UserOutlined } from '@ant-design/icons'
import { useForm } from 'antd/es/form/Form'
import { Link, useNavigate } from 'react-router-dom'
import { useRequest } from 'ahooks'
import { login } from '@/service/module/user'
import { setToken } from '@/utils/user-token'

const { Title } = Typography

const USERNAME_KEY = 'USERNAME'
const PASSWORD_KEY = 'PASSWORD'

const rememberUser = (username: string, password: string) => {
  localStorage.setItem(USERNAME_KEY, username)
  localStorage.setItem(PASSWORD_KEY, password)
}

const removeUser = () => {
  localStorage.removeItem(USERNAME_KEY)
  localStorage.removeItem(PASSWORD_KEY)
}

const getUserInfo = () => {
  return {
    username: localStorage.getItem(USERNAME_KEY),
    password: localStorage.getItem(PASSWORD_KEY),
  }
}

const Login = memo(() => {
  const [form] = useForm()

  const nav = useNavigate()

  const onFinish = (values: any) => {
    const { username, password, remember } = values
    run(username, password)
    if (remember) {
      rememberUser(username, password)
    } else {
      removeUser()
    }
  }

  const { run } = useRequest(
    async (username = '', passowrd = '') => {
      const data = await login(username, passowrd)
      return data
    },
    {
      manual: true,
      onSuccess(result) {
        const { token = '' } = result
        message.success('登录成功')
        setToken(token) //存储token
        nav('/manage')
      },
    }
  )

  useEffect(() => {
    const { username, password } = getUserInfo()
    form.setFieldsValue({ username, password })
  }, [])

  return (
    <div className={styles.container}>
      <div>
        <Space>
          <Title level={2}>
            <UserOutlined />
          </Title>
          <Title level={2}>用户登录</Title>
        </Space>
      </div>

      <div>
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: '请输入用户名~',
              },
              {
                type: 'string',
                min: 5,
                max: 20,
                message: '字符长度在 5-20 之间',
              },
              {
                pattern: /^\w+$/,
                message: '只能是字母数字下划线',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item name="remember" valuePropName="checked" label={null}>
            <Checkbox>记住密码</Checkbox>
          </Form.Item>
          <Form.Item label={null}>
            <Space>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
              <Link to="/register">注册新用户</Link>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
})

export default Login
